package com.gmail.avereshchaga.db.dao;

import com.gmail.avereshchaga.db.entity.IUser;
import com.gmail.avereshchaga.db.entity.UserImpl;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
@Repository
public class UserDAOImpl implements IUserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public List<IUser> findByName(String name) {
        Session session = sessionFactory.getCurrentSession();
        Criteria crit = session.createCriteria(UserImpl.class);
        crit.add(Restrictions.or(Restrictions.ilike("lastName", name),
                Restrictions.ilike("firstName", name)));
        List<IUser> users = crit.list();
        return users;
    }

    @Override
    public UserImpl findByUsernameAndPassword(String username, String password) {
        Session session = sessionFactory.getCurrentSession();
        Criteria crit = session.createCriteria(UserImpl.class);
        crit.add(Restrictions.and(Restrictions.eq("username", username),
                Restrictions.eq("password", password)));
        UserImpl user = (UserImpl) crit.uniqueResult();
        return user;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
}
